1
1
.
.
3
3
.
.
2
2
S
S
c
c
h
h
e
e
d
d
u
u
l
l
e
e
d
d
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
This tutorial shows how to use @Scheduled Annotation to periodically run methods (in the future).
To schedule a Method you just need to use @Scheduled(fixedDelay=5000) Annotation.
To enable @Scheduled Annotation you need to add @EnableScheduling to some @Configuration Class.
Method's Class must be declared as Spring Component for Spring to detect it.
In this example this is achieved also by @Configuration (so @Configuration has dual role in this example).
@Scheduled Parameters (milliseconds)
@Scheduled(fixedRate = 5000) //Measured from the START of previous task
@Scheduled(fixedDelay = 5000) //Measured from the END of previous task
@Scheduled(fixedDelay = 5000, initialDelay = 1000) //Delay before first execution
@Scheduled(cron="*/5 * * * * MON-FRI") //Execute on weekdays
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
To keep the Application running
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_taskscheduler.tasks (add Spring Boot Starters from the table)
Create Package: tasks (inside main package)
– Create Class: MyTasks.java (inside runners package)
MyTasks.java
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class MyTasks {
@Scheduled(fixedDelay=5000)
public void task1() {
System.out.println("Hello from task1()");
}
}
MyTasks
R
R
e
e
s
s
u
u
l
l
t
t
s
s
Console
Hello from task1()
Hello from task1()
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>